import { modal } from 'vue-strap'
import { showMsg, updateInvester } from '../../../../../vuex/action.js'
import extend from 'extend'

export default {
  name: 'Update-Invester',
  data() {
    return {
      showUpdateInvester: false,
      invester: {
        uid: '',
        name: '',
        img: '',
        org: '',
        cardNum: ''
      }
    }
  },
  props: ['updateInvester'],
  methods: {
    checkNullOrUndefined(val) {
      if (val === null || val === undefined) {
        return ''
      }
      return val
    },
    trim(str) {
      str = this.checkNullOrUndefined(str)
      if (typeof str === 'string') {
        return str.replace(/(^ +)|( +$)/g, '')
      }
      return str
		},
    validCheck() {
      let inputs = ['org', 'cardNum']
      let key
      let invester = this.invester
      for (key of inputs) {
        if (!invester[key] || invester[key].length === 0) {
          return '* 标记的都为必填项'
        }
      }
    },
    evtShowUpdateInvester() {
      this.invester = extend(true, {}, this.updateInvester)
      this.invester.imgUrl = this.updateInvester['img']
      this.showUpdateInvester = true
    },
    evtUpdateInvester() {
      let msg = this.validCheck()
      if (msg) {
        return this.xShowMsg({
          type: 'danger',
          content: msg
        })
      }

      let formData = new FormData()
      let file = this.$els.investerImage.files[0]
      Object.keys(this.invester).forEach((key) => {
        if (key === 'img') {
          if (file) {
            formData.append('img', file)
          }
        } else {
          formData.append(key, this.trim(this.invester[key]))
        }
      })

      this.xUpdateInvester(formData)
        .then(() => {
          this.$els.addForm.reset()
          this.showUpdateInvester = false
          this.$dispatch('on_refresh_list')
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xUpdateInvester: updateInvester
    }
  },
  components: {
    modal: modal
  },
  ready() {
  }
}
